package com.ruoyi.common.utils.http;

import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @description todo
 * @data 2025/9/24 13:50
 */
@Component
public class HttpClientUtil {

    private final OkHttpClient okHttpClient;

    public HttpClientUtil() {
        this.okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 发送POST请求
     */
    public String post(String url, String jsonBody, Map<String, String> headers) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = null;
        try {
            /*RequestBody body = RequestBody.Companion.create(
                    jsonBody, MediaType.parse("application/json; charset=utf-8"));*/
            // 根据OkHttp版本选择创建方式
            try {
                // 尝试OkHttp 4.x的方式 (String, MediaType)
                body = RequestBody.create(jsonBody, mediaType);
            } catch (Error e) {
                // 使用OkHttp 3.x的方式 (MediaType, String)
                body = RequestBody.create(mediaType, jsonBody);
            }


            Request.Builder builder = new Request.Builder()
                    .url(url)
                    .post(body);

            // 添加请求头
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }

            Request request = builder.build();

            try (Response response = okHttpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code: " + response);
                }
                return response.body().string();
            }
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求失败", e);
        }
    }
}
